import {
  login,
  getUserInfo,
  listByUserId,
  updatePassword
} from '@/api/upms/user-setting'
import { getDeptById } from '@/api/upms/dept'
import { setToken } from '@/utils/auth'
import router from '@/router'
import CryptoJS from 'crypto-js'
const state = {
  user: null, // 用户信息
  dept: null, // 用户归属部门
  roleList: [], // 用户角色列表
  token: null // 用户Token
}

const mutations = {
  USER: (state, user) => {
    state.user = user
  },
  DEPT: (state, dept) => {
    state.dept = dept
  },
  ROLE_LIST: (state, roleList) => {
    state.roleList = roleList
  },
  TOKEN: (state, token) => {
    state.token = token
  }
}

const actions = {
  user({ commit }, user) {
    commit('USER', user)
  },
  dept({ commit }, dept) {
    commit('DEPT', dept)
  },
  roleList({ commit }, roleList) {
    commit('ROLE_LIST', roleList)
  },
  token({ commit }, token) {
    commit('TOKEN', token)
  },
  updatePassword({ username, password }) {
    console.log('%o', { username, password })
    updatePassword({
      username: username,
      password: CryptoJS.SHA1(password).toString()
    }).then(result => {
      // 重置密码成功
    })
  },
  login(store, { username, password }) {
    const { commit, rootState } = store
    login({
      username: username,
      password: CryptoJS.SHA1(password).toString()
    })
      .then(result => {
        if (result.code === 500) {
          console.log(result.message)
        } else {
          console.log('%o', result.data)
          setToken(result.data)
          return getUserInfo(username) // 获取用户基础信息
        }
      })
      .then(result => {
        commit('USER', result.data)
        console.log('%o', result.data)
        return getDeptById(result.data.deptId) // 获取用户归属部门信息
      })
      .then(result => {
        commit('DEPT', result.data)
        console.log('%o', result.data)
        return listByUserId(rootState.user.user.id) // 获取用户角色链
      })
      .then(result => {
        commit('ROLE_LIST', result.data)
        console.log('%o', result.data)
        router.push('/')
      })
      .catch(err => {
        console.log('兜底：' + err)
      })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
